package com.xinbochuang.machine.admin.service.impl.system;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinbochuang.machine.admin.domain.system.SysDept;
import com.xinbochuang.machine.admin.domain.system.SysRole;
import com.xinbochuang.machine.admin.domain.system.SysRoleDept;
import com.xinbochuang.machine.admin.domain.system.SysUser;
import com.xinbochuang.machine.admin.mapper.system.SysDeptMapper;
import com.xinbochuang.machine.admin.service.system.ISysDeptService;
import com.xinbochuang.machine.admin.service.system.ISysRoleDeptService;
import com.xinbochuang.machine.admin.service.system.ISysUserService;
import com.xinbochuang.machine.common.annotation.DataScope;
import com.xinbochuang.machine.common.constant.UserConstants;
import com.xinbochuang.machine.common.domain.TreeSelect;
import com.xinbochuang.machine.common.enums.UserStatus;
import com.xinbochuang.machine.common.exception.CustomException;
import com.xinbochuang.machine.common.utils.SecurityUtils;
import com.xinbochuang.machine.common.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 黄晓鹏
 * @date 2020-09-23
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleDeptService roleDeptService;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> deptList) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Integer> tempList = new ArrayList<>();
        for (SysDept dept : deptList) {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<SysDept> iterator = deptList.iterator(); iterator.hasNext(); ) {
            SysDept dept = iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(deptList, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = deptList;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param deptList 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> deptList) {
        List<SysDept> deptTrees = buildDeptTree(deptList);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Integer roleId) {
        return deptMapper.selectDeptListByRoleId(roleId);
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Integer deptId) {
        return getById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Integer deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在部门子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Integer deptId) {
        int result = count(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getDelFlag, 0).eq(SysDept::getParentId, deptId).last("and rownum = 1"));
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Integer deptId) {
        int result = userService.count(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getDelFlag, 0).eq(SysUser::getDeptId, deptId));
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Integer deptId = dept.getDeptId() == null ? -1 : dept.getDeptId();
        SysDept info = getOne(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getDeptName, dept.getDeptName()).eq(SysDept::getParentId, dept.getParentId()).last("and rownum = 1"));
        if (StringUtils.isNotNull(info) && !deptId.equals(info.getDeptId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean insertDept(SysDept dept) {
        SysDept info = getById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new CustomException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return save(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean updateDept(SysDept dept) {
        SysDept newParentDept = getById(dept.getParentId());
        SysDept oldDept = getById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        return result > 0;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean deleteDeptById(Integer deptId) {
        SysDept dept = new SysDept();
        dept.setDeptId(deptId);
        dept.setDelFlag(UserStatus.DELETED.getCode());
        return updateById(dept);
    }

    /**
     * 根据数据权限查询部门树
     *
     * @return 结果
     */
    @Override
    public List<Integer> getDeptIdsByDataScope() {
        List<Integer> deptIds = new ArrayList<>();
        // 获取当前的用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!SecurityUtils.isAdmin(user.getUserId())) {
            for (SysRole role : user.getRoles()) {
                String dataScope = role.getDataScope();
                if ("2".equals(dataScope)) {
                    // 自定数据权限
                    List<SysRoleDept> roleDeptList = roleDeptService.list(Wrappers.<SysRoleDept>lambdaQuery().eq(SysRoleDept::getRoleId, role.getRoleId()));
                    for (SysRoleDept sysRoleDept : roleDeptList) {
                        deptIds.add(sysRoleDept.getDeptId());
                    }
                } else if ("3".equals(dataScope)) {
                    // 本部门数据权限
                    deptIds.add(user.getDeptId());
                } else if ("4".equals(dataScope)) {
                    // 本部门及以下数据权限
                    deptIds.addAll(deptMapper.selectDeptAndChild(user.getDeptId()));
                } else if ("5".equals(dataScope)) {
                    // 仅本人数据权限
                    deptIds.add(user.getDeptId());
                }
            }
        }
        return deptIds;
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Integer deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            updateBatchById(children);
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = getById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        dept.setUpdateTime(DateUtil.now());
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }
}
